package cn.itfei.lottery.domain.support.ids.policy;

import cn.itfei.lottery.domain.support.ids.IIdGenerator;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Random;

/**
 * @description:    短码生成策略，仅支持很小的调用量，用于生成活动配置类编号，保证全局唯一
 * @author：hfb
 * @date: 2023/11/11
 */
@Component
public class ShortCode implements IIdGenerator {
    @Override
    public synchronized Long nextId() { //加synchronized为了保证全局唯一ID
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        //  打乱排序：2020年为准 + 小时 + 周期 + 日 +三位随机数
        StringBuilder idstr = new StringBuilder();
        idstr.append(year - 2020);
        idstr.append(hour);
        idstr.append(String.format("%02d", week));
        idstr.append(day);
        idstr.append(String.format("%03d",new Random().nextInt(1000)));

        return Long.parseLong(idstr.toString());

    }
}
